package com.gitee.webdav.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author hongda.li
 */
public final class XmlHelper {
    private static final XmlMapper MAPPER = new XmlMapper();
    private static final Logger LOGGER = LoggerFactory.getLogger(XmlHelper.class);

    static {
        MAPPER.enable(SerializationFeature.INDENT_OUTPUT);
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    private XmlHelper() {
    }

    public static <Bean> String toXml(Bean bean) {
        try {
            return MAPPER.writeValueAsString(bean);
        } catch (JsonProcessingException e) {
            LOGGER.error("[Webdav] -- [Xml序列化失败]", e);
            throw new WebdavException(e);
        }
    }

    public static <Bean> Bean fromXml(String xml, Class<Bean> clazz) {
        try {
            return MAPPER.readValue(xml, clazz);
        } catch (JsonProcessingException e) {
            LOGGER.error("[Webdav] -- [Xml反序列化失败]", e);
            throw new WebdavException(e);
        }
    }

    public static <Bean> Bean fromXml(InputStream stream, Class<Bean> clazz) {
        try {
            return MAPPER.readValue(stream, clazz);
        } catch (IOException e) {
            LOGGER.error("[Webdav] -- [Xml反序列化失败]", e);
            throw new WebdavException(e);
        }
    }
}
